<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :loading="loading"
    :remote-method="remoteMethod"
    @change="updateValue"
    @keyup.enter.native="keyEntry"
    remote
    filterable
    remote-show-suffix
    clearable
    :default-first-option = "false"
    :dropdown-append-to-body="false"
    ref="modelRef"
  >
<!--    :reserve-keyword ="false"-->
    <el-option
      v-for="item in options"
      :key="item[fieldMappings.key]"
      :label="item[fieldMappings.label]"
      :value="item[fieldMappings.value]"
    />
  </el-select>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import { ElSelect, ElOption } from 'element-plus';

defineOptions({
  name: 'RemoteSearchSelect'
});

const props = defineProps({
  modelValue: [String, Number],
  placeholder: String,
  data: {} as any,
  fetchOptions: {
    type: Function,
    required: true
  },
  api: {
    type: Function,
    default: (query: any) => query
  },
  fieldMappings: {
    type: Object,
    default: () => ({
      key: 'id',
      label: 'label',
      value: 'value'
    })
  },
});

const emits = defineEmits(['update:modelValue','modelEntry','fatherMothed']);

const selectedValue = ref(props.modelValue);
const loading = ref(false);
const options = ref<any[]>([]);
const modelRef = ref()

const remoteMethod = async (query: string) => {
  console.log('remoteMethod triggered with query:', query);
  if (query) {
    loading.value = true;
    try {
      const queryParams = props.api(query);
      const result = await props.fetchOptions(queryParams);
      options.value = result.data;
    } catch (error) {
      console.error('Error fetching options:', error);
    } finally {
      loading.value = false;
    }
  }
};

const updateValue = (value: any) => {
  if (props.data){
    const selectedOption = options.value.find(option => option.id === value);
    emits('update:modelValue',value, props.data,selectedOption);
    return
  }

  emits('update:modelValue', value);
};


const keyEntry = (event: any) => {
    console.log('士大夫撒大范围防守打法',event.target.nextSibling.textContent)
    emits('modelEntry',event.target.nextSibling.textContent,props.data);
    emits('fatherMothed',props.data)
};


watch(
  () => props.modelValue,
  newValue => {
    selectedValue.value = newValue;
  }
);

</script>
